import { Component, PropsWithChildren, ReactElement } from 'react'
import styled from 'styled-components'

export class ErrorBoundary extends Component<
  PropsWithChildren<{
    fallbackRender?: (props: { error: Error | null }) => ReactElement
  }>,
  { error: Error | null }
> {
  state = { error: null }
  static getDerivedStateFromError(error: Error) {
    return { error }
  }
  render() {
    const { error } = this.state
    const { children, fallbackRender } = this.props

    if (error) {
      return fallbackRender ? (
        fallbackRender(error)
      ) : (
        <FullPage>{(error as Error).message}</FullPage>
      )
    }
    return children
  }
}

const FullPage = styled.div`
  display: flex;
  justify-content: center;
  height: 100vh;
  line-height: 100vh;
  text-align: center;
  color: red;
  font-weight: bold;
`
